<!-- 树状选择器 -->
<template>
  <el-popover
    ref="popover"
    placement="bottom-start"
    trigger="click"
    @show="onShowPopover"
    @hide="onHidePopover">
    <el-tree
      ref="tree"
      class="select-tree"
      highlight-current
      :style="`min-width: ${treeWidth}`"
      :data="datas"
       :show-checkbox="isMulti=='Y' ? true:false"
      :props="props"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :default-expand-all="true"
      :check-strictly="true"
      @check="onCheckNode"
      :node-key="props.value"
      @node-click="onClickNode">
    </el-tree>
    <el-input
      slot="reference"
      ref="input"
      v-model="labelModel"
      clearable
      style="width:160px"
      :class="{ 'rotate': showStatus }"
      suffix-icon="el-icon-arrow-down"
      :placeholder="placeholder">
    </el-input>
  </el-popover>
</template>

<script>
import Integer from '@zxing/library/esm/core/util/Integer';
export default {
  name: 'SelectTree',
  props: {
    // 接收绑定参数
    value: String,
    // 输入框宽度
    width: String,
    url:String,
    exkey:String||Object,
    index:String||Integer,
    id:String,
    data:Array,
    isMulti:String,
    // 选项数据
    options: {
      type: Array
    },
    // 输入框占位符
    placeholder: {
      type: String,
      required: false,
      default: '请选择',
    },
    // 树节点配置选项
    props: {
      type: Object,
      required: false,
      default: () => ({
        parent: 'pId',
        value: 'treeId',
        label: 'title',
        children: 'child',
      }),
    },
  },
  // 设置绑定参数
  model: {
    prop: 'value',
    event: 'selected',
  },
 /* computed: {
    // 是否为树状结构数据
   
    // 若非树状结构，则转化为树状结构数据
    data() {
      return this.dataType ? this.optionNews : this.switchTree();
    },
  },*/
  watch: {
    /*labelModel(val) {
      if (!val) {
        this.valueModel = '';
      }
      this.$refs.tree.filter(val);
    },*/
    value(val) {
      console.log("value==========="+val)
      this.labelModel = this.queryTree(this.data, val);
    },
    labelModel(val){
      console.log("labelModel============"+val)
      if(!val){
        this.valueModel="";
        let valueModel="";
       // try{
              if(this.index=="0"||this.index)
                this.$set(this.data[Number(this.index)],"vals",valueModel);
              else if(this.id){
                console.log("pId==="+this.pId+"=="+this.cId)
                this.$set(this.data[this.pId],this.cId,val);

                if(this.isJson(this.exkey)){  
                    for(let key in this.exkey){
                      if(key=="id"){
                        this.keyField=this.exkey[key];
                        this.$set(this.data[this.pId],this.keyField,valueModel);
                      }else{
                        let field=this.exkey[key];
                        let vals="";
                        for(let i=0;i<nodes.length;i++){
                          let node=nodes[i]
                          if(i==0){
                            vals = node[field];
                          }else{
                            if((","+vals+",").indexOf(","+node[field]+",")==-1){
                              vals=vals+","+node[field];
                            }
                          }
                        
                        }
                        
                        this.$set(this.data[this.pId],key,vals);
                      }
                    }
                }else{
                   this.$set(this.data[this.pId],this.exkey,valueModel);
                   this.keyField=this.exkey;
                }
               

                
              }else{
               /* let item={};
                item.label=labelModel;
                item.value=valueModel;
                this.$emit("input",JSON.stringify(item))*/

              }
           // }catch(e){

          //  }
            console.log("labelModel=="+this.labelModel+"="+valueModel)
            let item={};
            item.label=val;
            item.value=valueModel;
            this.$emit("input",JSON.stringify(item))
      }
    }
  },
  data() {
    return {
      // 树状菜单显示状态
      showStatus: false,
      // 菜单宽度
      treeWidth: 'auto',
      // 输入框显示值
      labelModel: '',
      // 实际请求传值
      valueModel: '0',
      optionNews:[],
      datas:[],
      pId:"",
      cId:"",
      keyField:""
    };
  },
  created() {

    // 检测输入框原有值并显示对应 label
    console.log("this.value=========="+this.value+"=="+this.labelModel)
    if (this.value) {
      this.labelModel = this.queryTree(this.datas, this.value);
    }
    // 获取输入框宽度同步至树状菜单宽度
   /* this.$nextTick(() => {
      this.treeWidth = `${(this.width || this.$refs.input.$refs.input.clientWidth) - 24}px`;
    });*/
   // alert(this.url)

   
   try{
     if(this.id){
      let ids=this.id.split(".");
      this.pId=ids[0];
      this.cId=ids[1]
      this.labelModel=this.data[this.pId][this.cId]
      if(this.exkey){
        let id=this.exkey.id;
        this.valueModel=this.data[this.pId][id];
      }
      
    }
    console.log("labelModels========="+this.labelModel+"=="+this.valueModel+"=="+this.url)
   }catch(e){}
   
    if(!this.options&&this.url){
     
        this.$post("",this.url,{value:this.valueModel}).then(data=>{
            if(data.data)
             this.optionNews=data.data;
             else
               this.optionNews=data;
            console.log("this.dataYpe[[[=====]]]==="+this.dataType)
            this.datas=this.dataType ? this.optionNews : this.switchTree();
            this.$nextTick(() => {
              if(data.labelModel){
                this.labelModel=data.labelModel;
             
                
                if(this.pId&&this.cId){
                  this.data[this.pId][this.cId]=this.labelModel
                }
              }
              
                //this.valueModel=this.value.split(",");
             
             
              
                //this.treeWidth = `${(this.width || this.$refs.input.$refs.input.clientWidth) - 24}px`;
            });
        })
    }else{
      this.datas=this.options;
      console.log("options==================================")
      console.log(this.datas)
    }

  },
  methods: {
    isJson(obj){
      var isjson = typeof(obj) == "object";   
      return isjson;
    },
     dataType() {
      const jsonStr = JSON.stringify(this.optionNews);
      return jsonStr.indexOf(this.props.children) !== -1;
    },
    onCheckNode(data,checked){
      if(this.isMulti=='Y'){
          let nodes=this.$refs.tree.getCheckedNodes()
          let labelModel="";
          let valueModel="";
          for(let i=0;i<nodes.length;i++){
            let node=nodes[i]
            if(i==0){
              labelModel = node[this.props.label];
              valueModel = node[this.props.value];
            }else{
              labelModel = labelModel+","+node[this.props.label];
              valueModel = valueModel+","+node[this.props.value];
            }
          
          
          
          }
          this.labelModel=labelModel;
          this.valueModel=valueModel;
          try{
              if(this.index=="0"||this.index)
                this.$set(this.data[Number(this.index)],"vals",valueModel);
              else if(this.id){
                this.$set(this.data[this.pId],this.cId,labelModel);

                if(this.isJson(this.exkey)){  
                    for(let key in this.exkey){
                      if(key=="id"){
                        this.keyField=this.exkey[key];
                        this.$set(this.data[this.pId],this.keyField,valueModel);
                      }else{
                        let field=this.exkey[key];
                        let vals="";
                        for(let i=0;i<nodes.length;i++){
                          let node=nodes[i]
                          if(i==0){
                            vals = node[field];
                          }else{
                            if((","+vals+",").indexOf(","+node[field]+",")==-1){
                              vals=vals+","+node[field];
                            }
                          }
                        
                        }
                        
                        this.$set(this.data[this.pId],key,vals);
                      }
                    }
                }else{
                   this.$set(this.data[this.pId],this.exkey,valueModel);
                   this.keyField=this.exkey;
                }
               

                
              }else{
               /* let item={};
                item.label=labelModel;
                item.value=valueModel;
                this.$emit("input",JSON.stringify(item))*/

              }
            }catch(e){

            }
            let item={};
            item.label=labelModel;
            item.value=valueModel;
            this.$emit("input",JSON.stringify(item))
      }
      
      
    },
    // 单击节点
    onClickNode(node) {
      if(this.isMulti!='Y'){
        this.labelModel = node[this.props.label];
        this.valueModel = node[this.props.value];
        console.log(node)
       
        try{
          if(this.index=="0"||this.index)
            this.$set(this.data[Number(this.index)],"vals",this.valueModel);
          else if(this.id){
            
            this.$set(this.data[this.pId],this.cId,this.labelModel);
            
            if(this.isJson(this.exkey)){
                for(let key in this.exkey){
                    if(key=="id"){
                      this.keyField=this.exkey[key];
                      this.$set(this.data[this.pId],this.keyField,valueModel);
                    }else{
                      let field=this.exkey[key];
                      this.$set(this.data[this.pId],key,node[field]);
                    }
                  }
            }else{
             
               this.$set(this.data[this.pId],this.exkey,this.valueModel);
            }
           

            
          }else{
            let item={};
            item.label=this.labelModel;
            item.value=this.valueModel;
            this.$emit("input",JSON.stringify(item))

          }
        }catch(e){

        }
        
        this.onCloseTree();
      }
      
    },
    // 偏平数组转化为树状层级结构
    switchTree() {
      return this.cleanChildren(this.buildTree(this.optionNews, '0'));
    },
    // 隐藏树状菜单
    onCloseTree() {
      this.$refs.popover.showPopper = false;
    },
    // 显示时触发
    onShowPopover() {
      this.showStatus = true;
      this.$refs.tree.filter(false);
      if(this.isMulti=='Y'){
        
          if(this.isJson(this.exkey)){  
              this.keyField=this.exkey["id"]
          }else{
              this.keyField=this.exkey;
          }
          this.$refs.tree.setCheckedKeys(this.data[this.pId][this.keyField].split(","));
      }
       
    },
    // 隐藏时触发
    onHidePopover() {
      this.showStatus = false;
      this.$emit('selected', this.valueModel);
    },
    // 树节点过滤方法
    filterNode(query, data) {
      if (!query) return true;
      return data[this.props.label].indexOf(query) !== -1;
    },
    // 搜索树状数据中的 ID
    queryTree(tree, id) {
      let stark = [];
      stark = stark.concat(tree);
      while (stark.length) {
        const temp = stark.shift();
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children]);
        }
        if (temp[this.props.value] === id) {
          return temp[this.props.label];
        }
      }
      return '';
    },
    // 将一维的扁平数组转换为多层级对象
    buildTree(data, id = '0') {
      const fa = (parentId) => {
        const temp = [];
        for (let i = 0; i < data.length; i++) {
          const n = data[i];
          if (n[this.props.parent] === parentId) {
            n.children = fa(n.rowGuid);
            temp.push(n);
          }
        }
        return temp;
      };
      return fa(id);
    },
    // 清除空 children项
    cleanChildren(data) {
      const fa = (list) => {
        list.map((e) => {
          if (e.children.length) {
            fa(e.children);
          } else {
            delete e.children;
          }
          return e;
        });
        return list;
      };
      return fa(data);
    },
  },
};
</script>

<style>
  .el-input.el-input--suffix {
    cursor: pointer;
    overflow: hidden;
  }
  .el-input.el-input--suffix.rotate .el-input__suffix {
    transform: rotate(180deg);
  }
  .select-tree {
    max-height: 350px;
    overflow-y: scroll;
  }
  /* 菜单滚动条 */
  .select-tree::-webkit-scrollbar {
    z-index: 11;
    width: 6px;
  }
  .select-tree::-webkit-scrollbar-track,
  .select-tree::-webkit-scrollbar-corner {
    background: #fff;
  }
  .select-tree::-webkit-scrollbar-thumb {
    border-radius: 5px;
    width: 6px;
    background: #b4bccc;
  }
  .select-tree::-webkit-scrollbar-track-piece {
    background: #fff;
    width: 6px;
  }
</style>